<script>
import { debounce } from '@/utils/debounce';
import RightList from './RightList.vue';
export default {
  components: {
    RightList,
  },
  props: {
    toc: {
      type: Array
    }
  },
  data() {
    return {
      activeAnchor: '',
      debounceAnchor: null,

    }
  },
  computed: {
    tocWithSelect() {
      const getSelect = (t = []) => {
        return t.map(item => ({
          ...item,
          isSelected: item.anchor === this.activeAnchor,
          children: getSelect(item.children),
        }));
      };
      return getSelect(this.toc)
    },

    doms() {
      const dom = []
      const getAllAnchorDoms = (toc = []) => {
        toc.forEach(item => {
          dom.push(document.getElementById(item.anchor))
          item.children && getAllAnchorDoms(item.children)
        })
      }
      getAllAnchorDoms(this.toc)
      return dom
    }
  },
  methods: {
    // 点击时设置哈希值
    handselect(item) {
      location.hash = item.anchor;
    },

    // 设置activeAnchor
    setActiveAnchor(dom) {
      if (!dom) {
        return;
      }
      const rang = 100 //距离顶部距离的容错范围
      for (const item of this.doms) {
        const top = item.getBoundingClientRect().top;
        if (top < rang) {
          this.activeAnchor = item.id;
        } else if (top < rang && top > -rang) {
          this.activeAnchor = item.id;
          break;
        }
      }
    }
  },
  created() {
    this.debounceAnchor = debounce(this.setActiveAnchor, 50)
    this.$bus.$on('mainScroll', this.debounceAnchor)
  },
  beforeDestroy() {
    this.$bus.$off('mainScroll', this.debounceAnchor)
  },
}
</script>



<template>
  <div class="blog-toc-container">
    <h2>目录</h2>
    <RightList v-if="toc" :list="tocWithSelect" @select="handselect" />
  </div>
</template>



<style lang='less' scoped>
.blog-toc-container {
  width: 100%;
  height: 100%;

  h2 {
    margin: 10px 5px;
  }
}
</style>